cmake_minimum_required(VERSION 3.10)
project(lua_cpp_test LANGUAGES CXX)

# 设置 C++ 标准
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED True)

# 设置 Lua 库和头文件路径
set(LUA_INCLUDE_DIR "${CMAKE_SOURCE_DIR}/../install/include")
set(LUA_LIB_DIR "${CMAKE_SOURCE_DIR}/../install/bin")
set(LUA_DLL_DIR "${CMAKE_SOURCE_DIR}/../install/bin")

# 包含 Lua 头文件路径
include_directories(${LUA_INCLUDE_DIR})

# 添加可执行文件
add_executable(lua_cpp_test main.cpp)

# 链接 Lua 动态库
if (WIN32)
    target_link_libraries(lua_cpp_test ${LUA_LIB_DIR}/liblua.lib)
else()
    target_link_libraries(lua_cpp_test ${LUA_LIB_DIR}/liblua.so)
endif()

# 查找当前目录下的所有 Lua 文件
file(GLOB LUA_FILES "${CMAKE_SOURCE_DIR}/*.lua")

# 添加自定义命令，用 luac 编译 Lua 文件
foreach(LUA_FILE ${LUA_FILES})
    get_filename_component(LUA_FILE_NAME ${LUA_FILE} NAME)
    add_custom_command(
        OUTPUT "${CMAKE_BINARY_DIR}/${LUA_FILE_NAME}c"
        COMMAND ${LUA_DLL_DIR}/luac -o "${CMAKE_BINARY_DIR}/${LUA_FILE_NAME}c" ${LUA_FILE}
        DEPENDS ${LUA_FILE}
        COMMENT "Compiling ${LUA_FILE} to ${CMAKE_BINARY_DIR}/${LUA_FILE_NAME}c"
    )
    list(APPEND COMPILED_LUA_FILES "${CMAKE_BINARY_DIR}/${LUA_FILE_NAME}c")
endforeach()

# 添加自定义目标，编译所有 Lua 文件
add_custom_target(compile_lua_files ALL DEPENDS ${COMPILED_LUA_FILES})

# 安装可执行文件
install(TARGETS lua_cpp_test
    RUNTIME DESTINATION ${CMAKE_INSTALL_PREFIX}/bin
)

# 安装 Lua 动态库
if (WIN32)
    install(FILES ${LUA_DLL_DIR}/liblua.dll
        DESTINATION ${CMAKE_INSTALL_PREFIX}/bin
    )
else()
    install(FILES ${LUA_DLL_DIR}/liblua.so
        DESTINATION ${CMAKE_INSTALL_PREFIX}/lib
    )
endif()

# 安装编译后的 Lua 字节码文件
install(FILES ${COMPILED_LUA_FILES}
    DESTINATION ${CMAKE_INSTALL_PREFIX}/bin
)
